package com.globalwave.common.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.globalwave.base.BaseServiceImpl;
import com.globalwave.common.cache.CodeHelper;
import com.globalwave.common.entity.Field;
import com.globalwave.common.entity.View;
import com.globalwave.common.entity.VirtualEditForm;

public class AttributesTemplateServiceImpl 
       extends BaseServiceImpl 
       implements AttributesTemplateService {

	private ViewService viewService ;

    public VirtualEditForm getUIMetaData(Long masterId, String viewCode) throws Exception {
    	VirtualEditForm form =  this.viewService.getEditFormMetaData(viewCode) ;
    	
    	if (masterId != null) {
	    	Map<String, String> defaultValues = getAll(masterId, form.getView()) ;
	    	List<Field> fields = form.getFields();
	    	
	    	for (Field f:fields) {
	    		final String value = defaultValues.get(f.getCode_()) ;
	    		f.setDefault_(value == null?"":value) ;
	    	}
    	}
    	
    	return form ;
    }
    
    
    public void create(Long masterId, Map<String, String[]> entity, Long viewId) throws Exception {
    	
    	View view = viewService.get(viewId)  ;

        jdbcDao.executeSQL(view.getBefore_sql_1(), new Object[]{masterId}) ;// delete all record relate to masterId
        
        for (Map.Entry<String, String[]> attr:entity.entrySet()) {
        	jdbcDao.executeSQL(view.getBefore_sql_2(), new Object[]{masterId, attr.getKey(), attr.getValue()[0]}) ;
        }
    	
    }

    

    public void deleteAll(Long masterId,Long viewId) throws Exception {
        
    	View view = viewService.get(viewId) ;
    	
        jdbcDao.executeSQL(view.getBefore_sql_1(), new Object[]{masterId}) ;// delete all record relate to masterId
        
    }

    public Map<String, String> getAll(Long masterId, View view) throws Exception {
    	Map<String, String> result = new HashMap<String, String>();
    	
        JdbcTemplate t = new JdbcTemplate() ;
        t.setDataSource((DataSource)CodeHelper.getAppContext().getBean("dataSource")) ;
        List<Map<String, Object>> attrs = t.queryForList(view.getBefore_sql_1(), new Object[]{masterId}) ;
        
        for (Map<String, Object> attr:attrs) {
        	result.put((String)attr.get("code_"), (String)attr.get("value_")) ;
        }
        
    	return result ;
    }

}
